/*
 * Copyright (c) 2018-2999 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.domain.Result;
import com.lam.common.context.TokenUtils;
import com.lam.common.utils.NumberUtil;
import com.lam.common.validate.ValidateUtil;
import com.lam.framework.operLog.annotation.Log;
import com.lam.mall.app.param.PayParam;
import com.lam.mall.app.vo.PayDataVo;
import com.lam.mall.entity.PayInfo;
import com.lam.mall.enums.PayStatus;
import com.lam.mall.enums.PayType;
import com.lam.mall.service.PayService;

/**
 */
@RestController
@RequestMapping("/${frontPath}/order")
@Log(title = "订单接口")
public class PayApiController {
	
	@Autowired
	private PayService payService;
	
    /**
     * 支付接口
     */
	@Log(oper = "H5支付")
    @PostMapping("/pay/h5")
    public Result pay(@Validated @RequestBody PayParam payParam) {
    	
		ValidateUtil.validRequired(payParam.getPayType(), "请选择支付方式！");
		ValidateUtil.validRequired(payParam.getOrderNumbers(), "订单号不能为空！");
		
        String userId = TokenUtils.getLoginUserid();
        
        PayDataVo payData = payService.pay(userId, payParam);
        if(NumberUtil.eq(PayType.MONI.code(), payParam.getPayType())) {
        	//模拟支付
        	payService.paySuccess(payData.getPayNo(), payData.getTradeNo(), PayType.MONI);
        	return Result.ok("模拟支付成功！").data(payData);
        }
        return Result.ok().data(payData);
    }

    /**
     * 支付结果查询
     */
    @PostMapping("/pay/h5/result")
    @Log(oper = "H5支付结果查询")
    public Result payQuery(@RequestBody PayParam payParam) {
    	
		ValidateUtil.validRequired(payParam.getPayNo(), "支付id不能为空！");
		
        PayInfo payInfo = payService.selectByPayNo(payParam.getPayNo());
        ValidateUtil.validRequired(payInfo, "支付信息不存在！");
        //判断是否已经支付过
        if(NumberUtil.eq(payInfo.getPayStatus(), PayStatus.PAYED.value())) {
        	return Result.ok().data(true);
        }
        
        return Result.ok().data(payService.queryPayResult(payInfo.getPayId(), payInfo.getBizPayNo(), payInfo.getPayType()));
    }
}
